package cn.ibdsr.human.constant;

import cn.ibdsr.human.util.HttpServletUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

/**
 * @description 有对外接口返回结果的封装类
 * @author chenglx
 * @version V1.0
 * @createDate 2019/10/29 11:23
 * <p>
 * Date Author Description
 * ------------------------------------------------------
 * 2019/10/29 chenglx init
 *
 */
@Data
@ApiModel("操作成功")
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -4202924309981220406L;
    /**
     * 处理是否成功
     */
    @ApiModelProperty("处理是否成功")
    private boolean success;
    /**
     * 处理成功时的业务数据
     */
    @ApiModelProperty("处理成功时的业务数据")
    private T model;
    /**
     * 处理失败时对应的 HTTP 响应状态码
     */
    @ApiModelProperty(" 处理失败时对应的 HTTP 响应状态码")
    private int httpStatusCode;
    /**
     * 处理失败时的错误信息
     */
    @ApiModelProperty("处理失败时的错误信息")
    private String errorMsg;

    private String message;
    /**
     * 先构造一个Result对象，后面再通过set方法设置数据
     */
    public Result() {}

    /**
     * 处理成功时的返回结果
     * @param model
     */
    public Result(T model) {
        this(true, model, 200, null);
    }

    /**
     * 处理失败时的返回结果
     * @param httpStatusCode
     * @param errorMsg
     */
    public Result(int httpStatusCode, String errorMsg) {
        this(false, null, httpStatusCode, errorMsg);
    }

    /**
     * 处理失败时的返回结果
     * @param errorType
     */
    public Result(ErrorTypeEnum errorType) {
        this(errorType.getHttpStatusCode(), errorType.getDesc());
    }

    /**
     * 全参数构造的返回结构
     * @param success
     * @param httpStatusCode
     * @param errorMsg
     */
    public Result(boolean success, T model, int httpStatusCode, String errorMsg) {
        this.success = success;
        this.model = model;
        this.httpStatusCode = httpStatusCode;
        this.errorMsg = errorMsg;
        this.message=errorMsg;
        setResponse(success, HttpServletUtils.getResponse(),this.httpStatusCode);
    }

    private void setResponse(boolean success, HttpServletResponse response, int httpStatusCode) {
        if (success) {
            response.setStatus(HttpServletResponse.SC_OK);
            return ;
        }
        response.setStatus(httpStatusCode);
    }
    public Class<T> obtainParameterizedType() {
        return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

}
